import os
import random
from datetime import datetime
import win32api
import win32gui
from _datetime import datetime
import win32con
import aircv as ac
from ctypes import windll
import time
from concurrent.futures import ThreadPoolExecutor
import win32ui
import tkinter
import tkinter.messagebox as messagebox
from tkinter import *
import hashlib


def clickLeftCur():
    win32api.mouse_event(win32con.MOUSEEVENTF_LEFTDOWN | win32con.MOUSEEVENTF_LEFTUP, 0, 0)


def leftDown(pos, hd):
    handle = hd
    client_pos = win32gui.ScreenToClient(handle, pos)
    tmp = win32api.MAKELONG(client_pos[0], client_pos[1])
    win32gui.SendMessage(handle, win32con.WM_ACTIVATE, win32con.WA_ACTIVE, 0)
    win32gui.SendMessage(handle, win32con.WM_LBUTTONDOWN, win32con.MK_LBUTTON, tmp)


def leftUp(pos, hd):
    handle = hd
    client_pos = win32gui.ScreenToClient(handle, pos)
    tmp = win32api.MAKELONG(client_pos[0], client_pos[1])
    win32gui.SendMessage(handle, win32con.WM_ACTIVATE, win32con.WA_ACTIVE, 0)
    win32gui.SendMessage(handle, win32con.WM_LBUTTONUP, win32con.MK_LBUTTON, tmp)


def click_it(pos, hd):
    handle = hd
    # moveCurPos(pos[0], pos[1])
    client_pos = win32gui.ScreenToClient(handle, pos)
    tmp = win32api.MAKELONG(client_pos[0], client_pos[1])
    win32gui.SendMessage(handle, win32con.WM_ACTIVATE, win32con.WA_ACTIVE, 0)
    win32gui.SendMessage(handle, win32con.WM_LBUTTONDOWN, win32con.MK_LBUTTON, tmp)
    win32gui.SendMessage(handle, win32con.WM_LBUTTONUP, win32con.MK_LBUTTON, tmp)


def click_it_a(pos, hd):
    handle = hd
    client_pos = win32gui.ScreenToClient(handle, pos)
    tmp = win32api.MAKELONG(client_pos[0], client_pos[1])
    win32gui.PostMessage(handle, win32con.WM_ACTIVATE, win32con.WA_ACTIVE, 0)
    win32gui.PostMessage(handle, win32con.WM_LBUTTONDOWN, win32con.MK_LBUTTON, tmp)
    win32gui.PostMessage(handle, win32con.WM_LBUTTONUP, win32con.MK_LBUTTON, tmp)


def moveCurPos(x, y):  # 移动鼠标
    windll.user32.SetCursorPos(x, y)


def getCurPos():  # 获得鼠标位置信息，这个再实际代码没用上，调试用得上
    return win32gui.GetCursorPos()


def dragCur(param, hd):
    leftDown((param[0], param[1]), hd)
    leftUp((param[0], param[1]), hd)


def matchImg(imgsrc, imgobj, confidence):  # imgsrc=原始图像，imgobj=待查找的图片
    """

    :rtype: object
    """
    imsrc = ac.imread(imgsrc)
    imobj = ac.imread(imgobj)
    match_result = ac.find_template(imsrc, imobj, confidence)
    # {'confidence': 0.5435812473297119, 'rectangle': ((394, 384), (394, 416), (450, 384), (450, 416)), 'result': (422.0, 400.0)}
    if match_result is not None:
        match_result['shape'] = (imsrc.shape[1], imsrc.shape[0])  # 0为高，1为宽

    return match_result


def window_capture(filename, hd):
    hwnd = hd  # 窗口的编号，0号表示当前活跃窗口
    # 根据窗口句柄获取窗口的设备上下文DC（Divice Context）
    hwndDC = win32gui.GetWindowDC(hwnd)
    # 根据窗口的DC获取mfcDC
    mfcDC = win32ui.CreateDCFromHandle(hwndDC)
    # mfcDC创建可兼容的DC
    saveDC = mfcDC.CreateCompatibleDC()
    # 创建bigmap准备保存图片
    saveBitMap = win32ui.CreateBitmap()
    # 获取监控器信息
    MoniterDev = win32api.EnumDisplayMonitors(None, None)
    w = MoniterDev[0][2][2]
    h = MoniterDev[0][2][3]
    # print(w, h)#图片大小
    # 为bitmap开辟空间
    saveBitMap.CreateCompatibleBitmap(mfcDC, w, h)
    # 高度saveDC，将截图保存到saveBitmap中
    saveDC.SelectObject(saveBitMap)
    # 截取从左上角（0，0）长宽为（w，h）的图片
    saveDC.BitBlt((0, 0), (w, h), mfcDC, (0, 0), win32con.SRCCOPY)
    saveBitMap.SaveBitmapFile(saveDC, filename)
    win32gui.DeleteObject(saveBitMap.GetHandle())
    saveDC.DeleteDC()


def get_all_hwnd(hwnd, mouse):
    if win32gui.IsWindow(hwnd) and win32gui.IsWindowEnabled(hwnd) and win32gui.IsWindowVisible(hwnd):
        hwnd_title.update({hwnd: win32gui.GetWindowText(hwnd)})


def get():
    list = [];
    win32gui.EnumWindows(get_all_hwnd, 0)
    for h, t in hwnd_title.items():
        if t != "":
            # if t == '夜神模拟器':
            if t == '阴阳师-网易游戏':
                list.append(h)
                # print(h)
    return list;


def loop(hwnd):
    # 定义一个字典（Java叫map），存储每个图片点击之后需要sleep的时间，为了优化cpu占用
    dict = {}
    for filename in os.listdir(r"../images/images-fight"):
        dict[filename] = 1

    # dict['4.png'] = 8
    curFileName = ""
    t1 = datetime.now()
    t2 = datetime.now()
    while state[hwnd] == 1:
        # print("state:", state)
        # ZMJ_PORTAL.write_log_to_Text(state)
        dict['1.png'] = 2
        dict['2.png'] = 2
        # time.sleep(8)
        baseImg = "../images/" + str(hwnd) + ".jpg"  # 储存的文件名  # 储存的文件名
        # print(baseImg)
        rect = win32gui.GetWindowRect(hwnd)
        window_capture(baseImg, hwnd)  # 对整个屏幕截图，并保存截图为baseImg
        # 遍历所有图片
        for filename in os.listdir(r"../images/images-fight"):  # listdir的参数是文件夹的路径
            imagePath = "../images/images-fight/" + filename
            print(imagePath)
            res = matchImg(baseImg, imagePath, 0.8)

            t2 = datetime.now()
            count = (t2 - t1).seconds
            # if count > 50:
            #     return ''
            if res is None:
                continue
            if filename == "reward.png":
                x = rect[0] + 20
                y = rect[1] + 560
            else:
                x = rect[0] + res["result"][0]
                y = rect[1] + res["result"][1]
            t2 = datetime.now()
            # 记录一下从上一个图片到开始点击需要多少秒，并记录下来
            dict[curFileName] = (t2 - t1).seconds

            curFileName = filename
            move_x = random.randint(int(x) - 2, int(x) + 2)
            move_y = random.randint(int(y) - 2, int(y) + 2)
            print(move_x, move_y)
            ZMJ_PORTAL.write_log_to_Text(str(move_x) + "," + str(move_y))
            click_it((move_x, move_y), hwnd)
            # 重新计时
            t1 = datetime.now()

            print(hwnd, dict)
            ZMJ_PORTAL.write_log_to_Text(str(hwnd) + ":" + str(dict))


hwnd_title = dict()


def helloCallBack(pool, hd):
    # messagebox.showinfo("Hello Python", "Hello Runoob")
    print(hd)


pool = ThreadPoolExecutor(max_workers=5)


def main():
    print("欢迎来到阴阳师联盟！")

    gui_start()



LOG_LINE_NUM = 0

list = get()

state = {}
for hd in list:
    state[hd] = 0


class MY_GUI():
    def __init__(self, init_window_name):
        self.init_window_name = init_window_name

    # 设置窗口
    def set_init_window(self):
        self.init_window_name.title("阴阳师辅助工具")  # 窗口名
        screenWidth = self.init_window_name.winfo_screenwidth()  # 获取显示区域的宽度
        screenHeight = self.init_window_name.winfo_screenheight()  # 获取显示区域的高度
        width = 530  # 设定窗口宽度
        height = 260  # 设定窗口高度
        left = (screenWidth - width) / 2
        top = (screenHeight - height) / 2
        self.init_window_name.geometry("%dx%d+%d+%d" % (width, height, left, top))

        self.log_label = Label(self.init_window_name, text="日志")
        self.log_label.grid(row=12, column=0)
        # 文本框

        self.log_data_Text = Text(self.init_window_name, width=66, height=9)  # 日志框
        self.log_data_Text.grid(row=13, column=0, columnspan=10)
        # 按钮

        if len(list) == 1:
            self.str_trans_to_md5_button1 = Button(self.init_window_name, text="句柄-" + str(list[0]),
                                                  bg="lightblue", command=self.str_trans_to_md51)
            self.str_trans_to_md5_button1.grid(row=5, column=2)
        elif len(list) == 2:
            print('两个客户端')
            self.str_trans_to_md5_button1 = Button(self.init_window_name, text="句柄-" + str(list[0]),
                                                   bg="lightblue", command=self.str_trans_to_md51)
            self.str_trans_to_md5_button1.grid(row=5, column=2)

            self.str_trans_to_md5_button2 = Button(self.init_window_name, text="句柄-" + str(list[1]),
                                                   bg="lightblue", command=self.str_trans_to_md52)
            self.str_trans_to_md5_button2.grid(row=5, column=4)
        elif len(list) == 3:
            self.str_trans_to_md5_button1 = Button(self.init_window_name, text="句柄-" + str(list[0]),
                                                   bg="lightblue", command=self.str_trans_to_md51)
            self.str_trans_to_md5_button1.grid(row=5, column=2)

            self.str_trans_to_md5_button2 = Button(self.init_window_name, text="句柄-" + str(list[1]),
                                                   bg="lightblue", command=self.str_trans_to_md52)
            self.str_trans_to_md5_button2.grid(row=5, column=4)

            self.str_trans_to_md5_button3 = Button(self.init_window_name, text="句柄-" + str(list[2]),
                                                   bg="lightblue", command=self.str_trans_to_md53)
            self.str_trans_to_md5_button3.grid(row=5, column=6)

    def str_trans_to_md51(self):
        hd = list[0]
        # 启动线程
        if state[hd] == 0:
            self.str_trans_to_md5_button1['bg'] = "lightgreen"
            state[hd] = 1
            pool.submit(loop, hd)
        else:
            self.str_trans_to_md5_button1['bg'] = "lightblue"
            # 停止线程
            state[hd] = 0
        self.write_log_to_Text(state)
        # self.write_log_to_Text("INFO:str_trans_to_md5 success")

    def str_trans_to_md52(self):
        hd = list[1]
        # 启动线程
        if state[hd] == 0:
            self.str_trans_to_md5_button2['bg'] = "lightgreen"
            state[hd] = 1
            pool.submit(loop, hd)
        else:
            self.str_trans_to_md5_button2['bg'] = "lightblue"
            # 停止线程
            state[hd] = 0
        self.write_log_to_Text(state)
        # self.write_log_to_Text("INFO:str_trans_to_md5 success")

    def str_trans_to_md53(self):
        hd = list[2]
        # 启动线程
        if state[hd] == 0:
            self.str_trans_to_md5_button3['bg'] = "lightgreen"
            state[hd] = 1
            pool.submit(loop, hd)
        else:
            self.str_trans_to_md5_button3['bg'] = "lightblue"
            # 停止线程
            state[hd] = 0
        self.write_log_to_Text(state)
        # self.write_log_to_Text("INFO:str_trans_to_md5 success")

    # 获取当前时间
    def get_current_time(self):
        current_time = time.strftime('%Y-%m-%d %H:%M:%S', time.localtime(time.time()))
        return current_time

    # 日志动态打印
    def write_log_to_Text(self, logmsg):
        global LOG_LINE_NUM
        current_time = self.get_current_time()
        logmsg_in = str(current_time) + " " + str(logmsg) + "\n"  # 换行
        if LOG_LINE_NUM <= 7:
            self.log_data_Text.insert(END, logmsg_in)
            LOG_LINE_NUM = LOG_LINE_NUM + 1
        else:
            self.log_data_Text.delete(1.0, 2.0)
            self.log_data_Text.insert(END, logmsg_in)


def on_closing():
    for hd in list:
        state[hd] = 0
    # init_window.deiconify()


    init_window.destroy()

    pool.shutdown(True)


init_window = Tk()

ZMJ_PORTAL = MY_GUI(init_window)


def gui_start():
    # 实例化出一个父窗口

    # 设置根窗口默认属性
    ZMJ_PORTAL.set_init_window()
    init_window.resizable(0, 0)
    init_window.protocol("WM_DELETE_WINDOW", on_closing)

    init_window.mainloop()  # 父窗口进入事件循环，可以理解为保持窗口运行，否则界面不展示


if __name__ == "__main__":
    main()
